package com.edouardbataille.open.bytes
{
	import flash.utils.ByteArray;

	public class ByteReader extends ByteArray
	{
		override public function readByte():int
		{
			return super.readByte() & 0xFF;
		}
		
		public function readPacketLength () : uint
		{
			var first : uint = readByte() & 0xFF;
			var second : uint = (readByte() & 0xFF) << 8;
			var third : uint =(readByte() & 0xFF) << 16;
			var res : uint = first + second + third;
			return res;
		}
		
		public function readPacketNum () : uint
		{
			return readByte();
		}
		
		public function readString (charSet : String) : String
		{
			var byte : int;
			var bytes : ByteArray = new ByteArray();
			while (bytesAvailable && (byte = readByte()) != 0x00)
			{
				bytes.writeByte(byte & 0xFF);
			}
			bytes.position = 0;
			return bytes.readMultiByte(bytes.length, charSet);
		}

		public function readLenString () : String
		{
			var length : uint = readLengthCode();
			if (length == 0)
				return null;
			return readUTFBytes(length);
		}

		public function readMultipleByte (offSet : uint) : uint
		{
			if (offSet == 0)
				return 0;
			var res : uint = readByte() & 0xFF;
			for (var i : int = 1; i < offSet; ++i)
			{
				res |= (readByte() & 0xFF) << (i * 8);
			}
			return res;
		}

		public function readLengthCode () : Number
		{
			var length : uint = readByte() & 0xFF;
			if (length <= 250)
				return length;

			if (length == 251)
				return 0;

			if (length == 252)
				return ((readByte() & 0xff)) + ((readByte() & 0xff) << 8);

			if (length == 253)
				return ((readByte() & 0xff)) + ((readByte() & 0xff) << 8) + ((readByte() & 0xff) << 16);

			if (length == 254)
				return ((readByte() & 0xff)) + ((readByte() & 0xff) << 8) + ((readByte() & 0xff) << 16) + ((readByte() & 0xff) << 24) | ((readByte() & 0xff) << 32) + ((readByte() & 0xff) << 40) + ((readByte() & 0xff) << 48) + ((readByte() & 0xff) << 56);
			return 0;
		}
		
		override public function readShort () : int
		{
			return readByte() & 0xFF | (readByte() & 0xFF) << 8
		}
		
		public function readUShort () : uint
		{
			return readByte() & 0xFF | (readByte() & 0xFF) << 8
		}

	}
}